package com.hzyl.famousreader.repository.persistence.dao;

import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.*;
import com.hzyl.famousreader.repository.persistence.entity.Book;
import com.hzyl.famousreader.repository.persistence.entity.BookChapter;

import java.util.Date;
import java.util.List;

/**
 * 书籍
 */
@Dao
public interface BookDao {

  /**
   * 查询书架列表
   *
   * @return
   */
  @Query("select * from book order by last_read_date desc")
  LiveData<List<Book>> selectBooks();

  /**
   * 查询是否已加入书架
   *
   * @param id
   * @return
   */
  @Query("select count(1) from book where id = :id")
  LiveData<Integer> selectCount(Long id);

  @Insert(onConflict = OnConflictStrategy.REPLACE)
  long insert(Book book);

  @Delete
  int delete(Book book);

  /**
   * 根据ID删除书籍
   *
   * @param id
   * @return
   */
  @Query("delete from book where id = :id")
  int deleteById(Long id);

  /**
   * 设置书籍的最后阅读时间
   * @param id
   * @param lastReadDate
   * @return
   */
  @Query("update book set last_read_date = :lastReadDate where id = :id")
  int updateLastReadDate(Long id, Date lastReadDate);

  /**
   * 更新书籍的历史查看记录
   * @param book
   * @return
   */
  @Update
  int updateChapterAndPage(Book book);

  /**
   * 根据书籍ID查询章节列表
   * @param id
   * @return
   */
  @Query("select * from chapter where book_id = :id order by sort asc")
  LiveData<List<BookChapter>> selectChaptersByBookId(Long id);

  /**
   * 批量插入章节列表
   * @param characters
   * @return
   */
  @Insert(onConflict = OnConflictStrategy.REPLACE)
  Long[] saveChapter(List<BookChapter> characters);

  /**
   * 根据书籍ID删除章节
   * @param id
   * @return
   */
  @Query("delete from chapter where book_id = :id")
  int deleteChapterByBookId(Long id);
}
